package org.x.gateway.exception;

import com.alibaba.fastjson2.JSON;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import org.x.common.base.result.Result;
import org.x.common.base.result.ResultCode;
import reactor.core.publisher.Mono;

import static org.x.common.base.result.ResultCode.NOT_FOUND;

@Order(-1) // 确保优先级高于默认处理器
public class GatewayGlobalExceptionHandler implements WebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);

        // 构建统一响应
        Result<?> result = Result.error(ResultCode.GATEWAY_ERROR);
        if (ex instanceof org.springframework.cloud.gateway.support.NotFoundException) {
            result = Result.error(NOT_FOUND);
        }

        byte[] bytes = JSON.toJSONBytes(result);
        DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
        return exchange.getResponse().writeWith(Mono.just(buffer));
    }
}